from rest_framework import serializers
import re
from meiduo_mall.utils.qq_sdk import OAuthQQ
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings

from .models import OAuthQQUser
from users.models import User
from meiduo_mall.utils import jwt_token

class OAuthQQUserSerializer(serializers.Serializer):
    '''
    定义属性
    定义验证方法
    创建或修改方法
    '''
    #接受值
    mobile=serializers.CharField(write_only=True)
    password=serializers.CharField(write_only=True)
    sms_code=serializers.IntegerField(write_only=True)
    access_token=serializers.CharField(write_only=True)

    #输出值
    user_id = serializers.IntegerField(read_only=True)
    username = serializers.CharField(read_only=True)
    token = serializers.CharField(read_only=True)

    #定义验证方法
    def validate_mobile(self,value):
        if not re.match(r'^1[3-9]\d{9}$',value):
            raise serializers.ValidationError('手机号错误')
        #当前是绑定，而不是注册，不需要判断手机号存在，
        return value

    def validate_access_token(self,value):
        openid=OAuthQQ.check_openid_token(value)
        if openid is None:
            raise serializers.ValidationError('身份信息无效')
        return openid
    def validate(self, attrs):
        #验证短信验证码
        return attrs

    #创建或修改方法
    def create(self,validated_data):

        mobile = validated_data.get('mobile')
        password = validated_data.get('password')
        openid=validated_data.get('access_token')
        #根据手机号查询对象
        try:
            user=User.objects.get(mobile=mobile)
        except:
            #如果不存在则新建对象并绑定
            #创建新用户对象
            user=User()
            user.mobile=mobile
            user.username=mobile
            user.set_password(password)
            user.save()
            #创建绑定对象
            oauthqqUser=OAuthQQUser()
            oauthqqUser.openid=openid
            oauthqqUser.user=user
            oauthqqUser.save()
            #响应
            user.token=jwt_token.get_token(user)
            return user
        else:
            #如果已经存在则判断手机号是否正确
            if not user.check_password(password):
                #如果不正确则返回错误
                raise serializers.ValidationError('帐号错误')
            #如果正确则绑定
            oauthqqUser = OAuthQQUser()
            oauthqqUser.openid = openid
            oauthqqUser.user = user
            oauthqqUser.save()
            #响应
            user.token = jwt_token.get_token(user)
            return user



